#include "algo_tarpa.h"

#include "tarpa/tarpa.h"

#include <unistd.h>
#include <time.h>
#include "modbus-srv.h"
#include "util.h"

/* Anti-warning macro... */
#define UNUSED(V) ((void) V)

struct tarpa_param{
    int pts[4];
    float black_ratio;
    float black_ratio_threshold;
} tarpaparam;

int init_tarpa(void* algo)
{
    UNUSED(algo);
    tarpaparam.black_ratio_threshold = 0.7;
    //int rect[4] = { 820, 180, 280, 220 }; // 安居roi
    int rect[4] = {882, 188 ,308, 546}; // 运河roi
    for (int i=0; i<4; i++) tarpaparam.pts[i] = rect[i];
    return 0;
}

void* compute_tarpa(void* algo, unsigned char* data, int width, int height)
{
    if (is_beam_signal_set() == 0) return NULL;
    
    
    reset_beam_signal();
    //reset_tarpa_alarm();
    //sleep(2);

    int avera_gray_value = 0;
    tarpaparam.black_ratio = tarpaDetect(data, width, height, tarpaparam.pts, &avera_gray_value);

    time_t t = time(NULL) + 3600*8;
    struct tm* tm = localtime(&t);
    char filename[512];
    sprintf(filename, "/var/tmp/%02d%02d_%02d%02d%02d_%.2f.raw",
    (tm->tm_mon+1), tm->tm_mday, tm->tm_hour, tm->tm_min,tm->tm_sec,tarpaparam.black_ratio);
    __write_file(filename, data, width*height);
    
    // 注意：这里随便返回一个非空的值，否则算法循环在这一步判断空后，analysis和response不执行。
    return &tarpaparam;
}

//void debug_tarpa(unsigned char* data, int width, int height)
//{}

void* analysis_tarpa(void* input)
{
    UNUSED(input);
    if (tarpaparam.black_ratio > tarpaparam.black_ratio_threshold) {
        __log_mesg("Detection result=>tarpa off(black-ratio=%.2f)\n", tarpaparam.black_ratio);
        return 1;
    }
    __log_mesg("Detection result=>tarpa on(black-ratio=%.2f)\n", tarpaparam.black_ratio);
    return 0; 
}

int response_tarpa(void* algo, void* input)
{
    int val = (int)input;
    if (val != 0) {
        set_tarpa_alarm();
    } else {
        reset_tarpa_alarm();
    }

    sleep(2);
    fill_tarpa_alarm();
    return 0;
}

void destroy_tarpa(void* algo)
{
    UNUSED(algo);
}